import { defineStore } from 'pinia'

/**
 * 用户搜索历史
 * @author lian
 */
export const useHistoryStore = defineStore('history', () => {
  /** 搜索历史 */
  const searchHistory = ref<string[]>([])

  // 添加搜索历史
  const addSearchHistory = (val: string) => {
    const index = searchHistory.value.indexOf(val)
    if (index !== -1) {
    // 如果存在该元素，先移除
      searchHistory.value.splice(index, 1)
    }
    searchHistory.value = [val, ...searchHistory.value.filter(item => item !== val)]
  }

  /**
   * 清空搜索历史
   */
  const clearSearchHistory = () => {
    searchHistory.value = []
  }

  return {
    searchHistory,
    addSearchHistory,
    clearSearchHistory,
  }
}, {
  persist: {
    storage: {
      setItem(key, value) {
        uni.setStorageSync(key, value)
      },
      getItem(key) {
        return uni.getStorageSync(key)
      },
    },
  },
})
